{% extends "base.html" %}

{% load i18n %}
{% load humanize %}
{% load btc_formats %}
{% load static %}

{% block title %}
  {% blocktrans with coin_display_name=coin_symbol|coin_symbol_to_display_name %}
    {{ coin_display_name }} Block Explorer
  {% endblocktrans %}
{% endblock title %}

{% block extra_head %}
{% endblock extra_head %}

{% block page_header %}
  <div class="col-lg-1 col-md-2 col-sm-3 col-xs-4 text-center">
    <div class="{{ coin_symbol }} coin"></div>
  </div>
  <div class="col-lg-11 col-md-10 col-sm-9 col-xs-8">
    <h1>{{ coin_symbol|coin_symbol_to_display_name }} Explorer</h1>
  </div>
{% endblock page_header %}

{% block content %}

<div class="container">

  <div class="ad">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8670884776365868"
           crossorigin="anonymous"></script>
    <!-- Main explorer -->
    <ins class="adsbygoogle"
           style="display:block;min-width:400px;max-width:970px;width:100%;height:90px"
                data-ad-client="ca-pub-8670884776365868"
                     data-ad-slot="7521279835"></ins>
    <script>
           (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
  </div>

  <div class="section">
    <h2>Recent Blocks</h2>

    <div class="table-responsive">
      <table class="table">
        <tr>
          <th>Height</th>
          <th>Age</th>
          <th>Transactions</th>
          <th>Total Sent</th>
          <th>Total Fees</th>
          <th>Block Size (in bytes)</th>
        </tr>
        {% for block in recent_blocks %}
          <tr>
            <td>
              <a href="{% url 'block_overview' coin_symbol block.height %}">{{ block.height }}</a>
            </td>
            <td>{{ block.received_time|naturaltime }}</td>
            <td>{{ block.n_tx|intcomma }}</td>
            <td>{% satoshis_to_user_units_trimmed block.total tcp__user_units coin_symbol True 5 %}</td>
            <td>{% satoshis_to_user_units_trimmed block.fees tcp__user_units coin_symbol True 5 %}</td>
            <td>{{ block.size|intcomma }}</td>
          </tr>
        {% endfor %}
      </table>
    </div>
  </div>

  <div class="section">
    <h2>Current Fee Estimates
      <a href="{{ fee_api_url }}" class="btn btn-default">
        <i class="fa fa-code"></i> 
        API Call
      </a>
      <a href="http://dev.blockcypher.com/#blockchain" class="btn btn-default">
        <i class="fa fa-external-link"></i> 
        API Docs
      </a>
    </h2>

    <div class="table-responsive">
      {% if coin_symbol == 'eth' %}
        <table class="table">
          <tr>
            <th>Recommended Gas Price <small>(1-4 blocks)</small></th>
          </tr>
          <tr>
            <td>
              <span>
                {% satoshis_to_user_units_trimmed fees.high_fee_per_kb 'gwei' coin_symbol 'True' 3 %}
              </span>
            </td>
          </tr>
        </table>
      {% else %}
        <table class="table">
          <tr>
            <th>High Priority <small>(1-2 blocks)</small></th>
            <th>Medium Priority <small>(3-6 blocks)</small></th>
            <th>Low Priority <small>(7+ blocks)</small></th>
          </tr>
          <tr>
            <td>
              <span>
                {% satoshis_to_user_units_trimmed fees.high_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}/KB
                <button
                  class="btn-link"
                  data-toggle="tooltip"
                  data-placement="bottom"
                  title="
                    About
                    {% satoshis_to_user_units_trimmed fees.high_fee_per_kb__smalltx tcp__user_units coin_symbol 'False' 3 %}
                    -
                    {% satoshis_to_user_units_trimmed fees.high_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}
                    per transaction, depending on the # of inputs/outputs
                    "
                >
                  <i class="fa fa-info-circle"></i>
                </button>
              </span>
            </td>
            <td>
              <span>
                {% satoshis_to_user_units_trimmed fees.medium_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}/KB
                <button
                  class="btn-link"
                  data-toggle="tooltip"
                  data-placement="bottom"
                  title="
                    About
                    {% satoshis_to_user_units_trimmed fees.medium_fee_per_kb__smalltx tcp__user_units coin_symbol 'False' 3 %}
                    -
                    {% satoshis_to_user_units_trimmed fees.medium_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}
                    per transaction, depending on the # of inputs/outputs
                    "
                >
                  <i class="fa fa-info-circle"></i>
                </button>
              </span>
            </td>
            <td>
              <span>
                {% satoshis_to_user_units_trimmed fees.low_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}/KB
                <button
                  class="btn-link"
                  data-toggle="tooltip"
                  data-placement="bottom"
                  title="
                    About
                    {% satoshis_to_user_units_trimmed fees.low_fee_per_kb__smalltx tcp__user_units coin_symbol 'False' 3 %}
                    -
                    {% satoshis_to_user_units_trimmed fees.low_fee_per_kb tcp__user_units coin_symbol 'True' 3 %}
                    per transaction, depending on the # of inputs/outputs
                    "
                >
                  <i class="fa fa-info-circle"></i>
                </button>
              </span>
            </td>
          </tr>
        </table>
      {% endif %}
    </div>
    <p>
      <i>
        Fee estimates are based on a rolling, weighted average.
      </i>
    </p>
  </div>

  <div class="section{% if not recent_txs %} hidden{% endif %}">
    <div id="newtx-section">
      <h2>Latest Transactions</h2>

      <div class="table-responsive">
        <table class="table">
          <tr id="latest-txs">
            <th>Transaction Hash</th>
            <th>{{ coin_symbol|coin_symbol_to_currency_name }}</th>
            <th>Time</th>
            <th>Miner Preference</th>
          </tr>
          <tr class="new-tx" style="display;none">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
          {% for recent_tx in recent_txs %}
            <tr class="new-tx">
              <td>
                <a href="{% url 'transaction_overview' coin_symbol recent_tx.hash %}">
                  {{ recent_tx.hash|slice:"12" }}
                </a>
                ...
              </td>
              <td>
                {# always in BTC/BCY/LTC/DOGE because JS streaming in new transactions will be and don't want to mix units #}
                {% if coin_symbol == 'eth' %}
                  {% satoshis_to_user_units_trimmed recent_tx.total 'ether' coin_symbol True 15 %}
                {% else %}
                  {% satoshis_to_user_units_trimmed recent_tx.total 'btc' coin_symbol %}
                {% endif %}
              </td>
              <td>
                <time class="timeago" datetime="{{ recent_tx.received|date:'Y-m-d\TH:i:s' }}Z">
                  {{ recent_tx.received|date:'Y-m-d H:i' }} GMT
                </time>
              </td>
              <td>
                {{ recent_tx.preference }}
              </td>
            </tr>
          {% endfor %}
        </table>
      </div>

      <p class="text-center">
        Note: BlockCypher is faster than other blockchain APIs, so these transactions may take a bit to appear on other sites.
      </p>

    </div>
  </div>

  <div class="section">
    <p class="text-center">
      <a class="btn btn-default" href="{% url 'push_tx' coin_symbol %}">Push Transaction</a>
      <a class="btn btn-default" href="{% url 'decode_tx' coin_symbol %}">Decode Raw Transaction</a>
    </p>
  </div>


</div>
{% endblock content %}

{% block extra_js %}

  <script src="{% static "js/jquery.timeago.js" %}" type="text/javascript"></script>

  <script>

    $(document).ready(function(){

      $("time.timeago").timeago();

      $('[data-toggle="tooltip"]').tooltip();

      var total_ws_received = 0;
      var MAX_WS_TO_RECEIVE = 100;

      function create_ws() {
        console.log('Creating new websocket...');
        ws = new WebSocket('{{ coin_symbol|coin_symbol_to_wss }}');
      }

      create_ws();

      function send_ping() {
        // Send pings at regular interval:
        if (total_ws_received < MAX_WS_TO_RECEIVE) {
          console.log('Sending websocket ping...');
          ws.send(JSON.stringify({event: "ping"}));
          // Trigger self recursively
          setTimeout(send_ping, 60000);
        } else {
          console.log('Not sending ping because MAX_WS_TO_RECEIVE reached');
        }
      }

      ws.onmessage = function(evt) {

        // Weak protection against too much activity
        total_ws_received += 1;
        if (total_ws_received > MAX_WS_TO_RECEIVE) {
          ws.close();
        }

        var data = JSON.parse(evt.data);
        // console.log(data);

        if ( data.hasOwnProperty('hash') && $('#' + data.hash).length == 0 ) {
          var btc_rounded = satoshis_to_btc_rounding(data.total);

          to_insert = $('<tr>').attr('class', "new-tx").attr('id', data.hash).append(
          $('<td>').append($('<a>').attr('href', '/{{ coin_symbol }}/tx/'+data.hash).text(data.hash.substring(0,12))).append('...'),
            $('<td>').append(btc_rounded+' {{ coin_symbol|coin_symbol_to_currency_name }}'),
            $('<td>').append($('<abbr>').attr('class', "timeago").attr('datetime', data.received)).text($.timeago(data.received)),
            $('<td>').text(data.preference)
          )
          $('.new-tx').first().before(to_insert);
          // Update the timing
          $("time.timeago").timeago();
          // New row effect:
          $('.new-tx').first().hide().fadeIn();

          if ( $('.new-tx').length > 10 ) {
            // Trim end of list once long
            $('.new-tx').last().fadeOut().remove();
          }

        }

      }

      ws.onopen = function() {
        console.log('Connection established.');
        ws.send(JSON.stringify({
          'event': 'unconfirmed-tx',
          'token': '{{ BLOCKCYPHER_PUBLIC_KEY }}',
        }));
        send_ping();
      };

      ws.onclose = function() {
        console.log('Connection closed');
        if (total_ws_received < MAX_WS_TO_RECEIVE) {
          console.log('Creating new websocket to replace old one...');
          create_ws();
        }

      };

      var sites = {
        piiko: "https://www.piiko.co",
        dashtext: "https://www.dashtext.io",
        texcent: "http://texcent.com",
				tradecore: "https://tradecore.com"
      };
      var ads = [];
      if (window.location.href.match(/dash/)) {
        ads = ["dashtext", "texcent", "tradecore"];
      } else if (window.location.href.match(/[bl]tc/)) {
        ads = ["texcent", "tradecore"];
      }
      if (ads.length > 0) {
        var chosen_idx = Date.now() % ads.length;
        var chosen_ad = ads[chosen_idx];
        var track_url = "https://live.blockcypher.com/ads/"+chosen_ad;

        $('#ad-link img').attr("src", "/static/img/" + chosen_ad + "_ad.png");
        $('#ad-link').attr("href", sites[chosen_ad]);
        $('#ad-link').click(function(e) {
          ga('send', 'event', 'outbound', 'click', track_url, {
            'transport': 'beacon',
            'hitCallback': function() {
              setTimeout(function() {
                document.location = sites[chosen_ad];
              }, 200);
            }
          });
          e.preventDefault();
          e.stopPropagation();
        });
        $('div.ad').show();
      }

    })

  </script>
{% endblock extra_js %}
